import React, { useState, useEffect } from 'react'
import { 
  Card, 
  Table, 
  Button, 
  Tag, 
  Space, 
  Input, 
  Modal,
  Form,
  message,
  Avatar,
  Tabs,
  Badge,
  Select,
  List
} from 'antd'
import { 
  TeamOutlined, 
  PlusOutlined, 
  EditOutlined, 
  DeleteOutlined,
  EyeOutlined,
  MessageOutlined,
  UserAddOutlined,
  StarOutlined,
  UserOutlined
} from '@ant-design/icons'
import dayjs from 'dayjs'
import { mockApi, UserProfile } from '@/services/mockData'

const { TabPane } = Tabs
const { Search } = Input

interface Community {
  id: string
  name: string
  description: string
  memberCount: number
  activeMembers: number
  createTime: string
  admin: string
  tags: string[]
}

interface CommunityPost {
  id: string
  title: string
  content: string
  author: string
  communityId: string
  likes: number
  comments: number
  createTime: string
}

const CommunityManagement: React.FC = () => {
  const [communities, setCommunities] = useState<Community[]>([])
  const [posts, setPosts] = useState<CommunityPost[]>([])
  const [users, setUsers] = useState<UserProfile[]>([])
  const [loading, setLoading] = useState(true)
  const [modalVisible, setModalVisible] = useState(false)
  const [activeTab, setActiveTab] = useState('communities')
  const [form] = Form.useForm()

  useEffect(() => {
    fetchData()
  }, [])

  const fetchData = async () => {
    setLoading(true)
    try {
      const usersData = await mockApi.getUserProfiles()
      setUsers(usersData)
      
      // 从localStorage获取社群数据，如果没有则使用模拟数据
      const storedCommunities = localStorage.getItem('communities')
      if (storedCommunities) {
        setCommunities(JSON.parse(storedCommunities))
      } else {
        // 模拟社群数据
        const communityData: Community[] = [
          {
            id: '1',
            name: '幸福村农业技术交流',
            description: '分享农业种植经验，交流技术心得',
            memberCount: 156,
            activeMembers: 89,
            createTime: '2024-01-15',
            admin: '1',
            tags: ['农业', '技术', '交流']
          },
          {
            id: '2',
            name: '乡村旅游发展联盟',
            description: '推广乡村旅游资源，打造特色品牌',
            memberCount: 234,
            activeMembers: 123,
            createTime: '2024-02-10',
            admin: '2',
            tags: ['旅游', '文化', '推广']
          },
          {
            id: '3',
            name: '农产品电商创业群',
            description: '农产品电商经验分享，创业指导',
            memberCount: 89,
            activeMembers: 45,
            createTime: '2024-03-01',
            admin: '3',
            tags: ['电商', '创业', '农产品']
          }
        ]
        setCommunities(communityData)
        localStorage.setItem('communities', JSON.stringify(communityData))
      }
      
      // 从localStorage获取帖子数据，如果没有则使用模拟数据
      const storedPosts = localStorage.getItem('posts')
      if (storedPosts) {
        setPosts(JSON.parse(storedPosts))
      } else {
        // 模拟帖子数据
        const postData: CommunityPost[] = [
          {
            id: '1',
            title: '春季水稻病虫害防治经验分享',
            content: '最近发现水稻出现了一些病虫害问题，大家有什么好的防治方法吗？',
            author: '1',
            communityId: '1',
            likes: 23,
            comments: 15,
            createTime: '2024-03-15 09:30'
          },
          {
            id: '2',
            title: '乡村旅游景点推荐',
            content: '推荐几个适合周末游的美丽乡村景点，环境优美，民风淳朴。',
            author: '2',
            communityId: '2',
            likes: 45,
            comments: 28,
            createTime: '2024-03-14 14:20'
          },
          {
            id: '3',
            title: '农产品电商运营技巧',
            content: '分享一些农产品电商的运营心得，希望能帮助到大家。',
            author: '3',
            communityId: '3',
            likes: 12,
            comments: 8,
            createTime: '2024-03-13 16:45'
          }
        ]
        setPosts(postData)
        localStorage.setItem('posts', JSON.stringify(postData))
      }
    } catch (error) {
      message.error('获取数据失败')
    } finally {
      setLoading(false)
    }
  }

  const handleCreateCommunity = () => {
    form.resetFields()
    setModalVisible(true)
  }

  const handleSubmit = async (values: any) => {
    try {
      const newCommunity: Community = {
        id: Date.now().toString(),
        name: values.name,
        description: values.description,
        memberCount: 1,
        activeMembers: 1,
        createTime: dayjs().format('YYYY-MM-DD'),
        admin: '1', // 默认当前用户为管理员
        tags: values.tags || []
      }
      
      const updatedCommunities = [newCommunity, ...communities]
      setCommunities(updatedCommunities)
      localStorage.setItem('communities', JSON.stringify(updatedCommunities))
      setModalVisible(false)
      message.success('社群创建成功')
    } catch (error) {
      message.error('创建失败')
    }
  }

  // 添加查看社群详情处理函数
  const handleViewCommunity = (community: Community) => {
    Modal.info({
      title: community.name,
      content: (
        <div>
          <p>描述: {community.description}</p>
          <p>成员数: {community.memberCount}</p>
          <p>活跃成员: {community.activeMembers}</p>
          <p>创建时间: {community.createTime}</p>
          <p>管理员: {getUserName(community.admin)}</p>
          <div style={{ marginTop: 8 }}>
            标签: {community.tags.join(', ')}
          </div>
        </div>
      ),
      onOk: () => console.log('查看社群详情')
    })
  }

  // 添加编辑社群处理函数
  const handleEditCommunity = (community: Community) => {
    form.setFieldsValue(community)
    setModalVisible(true)
    // 保存当前编辑的社群ID
    localStorage.setItem('editingCommunityId', community.id)
  }

  // 添加删除社群处理函数
  const handleDeleteCommunity = (communityId: string) => {
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除这个社群吗？',
      okText: '确定',
      cancelText: '取消',
      onOk: () => {
        const updatedCommunities = communities.filter(c => c.id !== communityId)
        setCommunities(updatedCommunities)
        localStorage.setItem('communities', JSON.stringify(updatedCommunities))
        message.success('删除成功')
      }
    })
  }

  // 添加查看帖子详情处理函数
  const handleViewPost = (post: CommunityPost) => {
    const community = communities.find(c => c.id === post.communityId)
    Modal.info({
      title: post.title,
      content: (
        <div>
          <p>内容: {post.content}</p>
          <p>作者: {getUserName(post.author)}</p>
          <p>所属社群: {community?.name || '未知社群'}</p>
          <p>点赞数: {post.likes}</p>
          <p>评论数: {post.comments}</p>
          <p>发布时间: {post.createTime}</p>
        </div>
      ),
      onOk: () => console.log('查看帖子详情')
    })
  }

  // 添加删除帖子处理函数
  const handleDeletePost = (postId: string) => {
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除这个帖子吗？',
      okText: '确定',
      cancelText: '取消',
      onOk: () => {
        const updatedPosts = posts.filter(p => p.id !== postId)
        setPosts(updatedPosts)
        localStorage.setItem('posts', JSON.stringify(updatedPosts))
        message.success('删除成功')
      }
    })
  }

  // 添加设为管理员处理函数
  const handleSetAdmin = () => {
    Modal.confirm({
      title: '设为管理员',
      content: '确定要将该用户设为管理员吗？',
      okText: '确定',
      cancelText: '取消',
      onOk: () => {
        message.success('设置成功')
      }
    })
  }

  const getUserName = (userId: string) => {
    const user = users.find(u => u.id === userId)
    return user?.name || '未知用户'
  }

  const communityColumns = [
    {
      title: '社群名称',
      dataIndex: 'name',
      key: 'name',
      render: (text: string, record: Community) => (
        <Space>
          <Avatar size="small" style={{ backgroundColor: '#1890ff' }}>
            {text.charAt(0)}
          </Avatar>
          <div>
            <div style={{ fontWeight: 500 }}>{text}</div>
            <div style={{ color: '#999', fontSize: 12 }}>{record.description}</div>
          </div>
        </Space>
      )
    },
    {
      title: '成员统计',
      key: 'members',
      render: (record: Community) => (
        <div>
          <div>总成员: {record.memberCount}</div>
          <div style={{ color: '#52c41a', fontSize: 12 }}>
            活跃: {record.activeMembers}
          </div>
        </div>
      )
    },
    {
      title: '管理员',
      dataIndex: 'admin',
      key: 'admin',
      render: (adminId: string) => getUserName(adminId)
    },
    {
      title: '标签',
      key: 'tags',
      render: (record: Community) => (
        <Space wrap>
          {record.tags.map(tag => (
            <Tag key={tag} color="blue">
              {tag}
            </Tag>
          ))}
        </Space>
      )
    },
    {
      title: '操作',
      key: 'action',
      render: (record: Community) => (
        <Space size="small">
          <Button 
            type="link" 
            icon={<EyeOutlined />} 
            size="small"
            onClick={() => handleViewCommunity(record)}
          >
            查看
          </Button>
          <Button 
            type="link" 
            icon={<EditOutlined />} 
            size="small"
            onClick={() => handleEditCommunity(record)}
          >
            编辑
          </Button>
          <Button 
            type="link" 
            danger 
            icon={<DeleteOutlined />} 
            size="small"
            onClick={() => handleDeleteCommunity(record.id)}
          >
            删除
          </Button>
        </Space>
      )
    }
  ]

  const postColumns = [
    {
      title: '帖子标题',
      dataIndex: 'title',
      key: 'title',
      render: (text: string) => <span style={{ fontWeight: 500 }}>{text}</span>
    },
    {
      title: '作者',
      dataIndex: 'author',
      key: 'author',
      render: (authorId: string) => getUserName(authorId)
    },
    {
      title: '所属社群',
      key: 'community',
      render: (record: CommunityPost) => {
        const community = communities.find(c => c.id === record.communityId)
        return community?.name || '未知社群'
      }
    },
    {
      title: '互动数据',
      key: 'interaction',
      render: (record: CommunityPost) => (
        <Space>
          <span>👍 {record.likes}</span>
          <span>💬 {record.comments}</span>
        </Space>
      )
    },
    {
      title: '发布时间',
      dataIndex: 'createTime',
      key: 'createTime',
      render: (time: string) => dayjs(time).format('MM-DD HH:mm')
    },
    {
      title: '操作',
      key: 'action',
      render: (record: CommunityPost) => (
        <Space size="small">
          <Button 
            type="link" 
            icon={<EyeOutlined />} 
            size="small"
            onClick={() => handleViewPost(record)}
          >
            查看
          </Button>
          <Button type="link" icon={<EditOutlined />} size="small">
            编辑
          </Button>
          <Button 
            type="link" 
            danger 
            icon={<DeleteOutlined />} 
            size="small"
            onClick={() => handleDeletePost(record.id)}
          >
            删除
          </Button>
        </Space>
      )
    }
  ]

  return (
    <div>
      <div className="page-title">
        <TeamOutlined />
        社群运营
      </div>

      <Tabs activeKey={activeTab} onChange={setActiveTab}>
        <TabPane tab={
          <span>
            <TeamOutlined />
            社群管理
          </span>
        } key="communities">
          <Card 
            title="社群列表"
            extra={
              <Space>
                <Search placeholder="搜索社群" style={{ width: 200 }} />
                <Button type="primary" icon={<PlusOutlined />} onClick={handleCreateCommunity}>
                  新建社群
                </Button>
              </Space>
            }
            className="custom-card"
          >
            <Table
              columns={communityColumns}
              dataSource={communities}
              loading={loading}
              rowKey="id"
              pagination={{
                total: communities.length,
                pageSize: 10,
                showSizeChanger: true
              }}
            />
          </Card>
        </TabPane>

        <TabPane tab={
          <span>
            <MessageOutlined />
            帖子管理
          </span>
        } key="posts">
          <Card 
            title="社群帖子"
            extra={<Search placeholder="搜索帖子" style={{ width: 200 }} />}
            className="custom-card"
          >
            <Table
              columns={postColumns}
              dataSource={posts}
              loading={loading}
              rowKey="id"
              pagination={{
                total: posts.length,
                pageSize: 10,
                showSizeChanger: true
              }}
            />
          </Card>
        </TabPane>

        <TabPane tab={
          <span>
            <UserAddOutlined />
            成员管理
            <Badge count={users.length} size="small" style={{ marginLeft: 8 }} />
          </span>
        } key="members">
          <Card title="社群成员" className="custom-card">
            <List
              dataSource={users}
              renderItem={(user: UserProfile) => (
                <List.Item>
                  <List.Item.Meta
                    avatar={<Avatar icon={<UserOutlined />} />}
                    title={
                      <Space>
                        <span>{user.name}</span>
                        <Tag color="blue">
                          {user.role === 'farmer' ? '农户' : 
                           user.role === 'village_admin' ? '村干部' : 
                           user.role === 'government' ? '政府人员' : '企业代表'}
                        </Tag>
                      </Space>
                    }
                    description={`${user.village} · ${user.phone}`}
                />
                <Button 
                  type="link" 
                  icon={<StarOutlined />}
                  onClick={handleSetAdmin}
                >
                  设为管理员
                </Button>
                </List.Item>
              )}
            />
          </Card>
        </TabPane>
      </Tabs>

      {/* 新建社群模态框 */}
      <Modal
        title="新建社群"
        open={modalVisible}
        onCancel={() => setModalVisible(false)}
        footer={null}
        width={600}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSubmit}
        >
          <Form.Item
            name="name"
            label="社群名称"
            rules={[{ required: true, message: '请输入社群名称' }]}
          >
            <Input placeholder="请输入社群名称" />
          </Form.Item>

          <Form.Item
            name="description"
            label="社群描述"
            rules={[{ required: true, message: '请输入社群描述' }]}
          >
            <Input.TextArea 
              rows={3} 
              placeholder="请输入社群描述" 
              maxLength={200}
              showCount
            />
          </Form.Item>

          <Form.Item
            name="tags"
            label="社群标签"
          >
            <Select mode="tags" placeholder="请输入标签" style={{ width: '100%' }} />
          </Form.Item>

          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit">
                {localStorage.getItem('editingCommunityId') ? '更新社群' : '创建社群'}
              </Button>
              <Button onClick={() => {
                setModalVisible(false)
                localStorage.removeItem('editingCommunityId')
              }}>
                取消
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  )
}

export default CommunityManagement